/**
 * 图片裁切工具
 *
 */

    //imgareaselect返回的对象，用avaInstance来调用imgareaselect返回的对象内部的函数
var avaInstance = "";
define(["util","text!/lib/upload/imgCropDialog.html"],
    function(xy_util,_cutDialog){
var xy_imgCrop = {
    paramsObj:{},
    init: function(params){
        if(!this.paramsObj[params.fileBtnId]){
            this.paramsObj[params.fileBtnId] = params;
        }
        this.initParam(params);
        this._creatDom();
        this._initDomListener();
        this._initImgUploader();
    },
    initParam: function(params){
        this.params = params;
        this.avaInstance = "";
        this.fileBtnId = params.fileBtnId;
        this.displayImg = params.displayImg;
        this.callback = params.callback == undefined ? "" : params.callback;
        this._saveformId = params.fileBtnId+"Form";
    },
    _creatDom: function(){
        this._creatFrom();
        this._createCutDialog()
    },
    _creatFrom: function(){
        if($("#"+this._saveformId).length == 0 ){
             var _form =[];
             _form.push('<form id="'+this._saveformId+'"style="position:absolute;top:335px;left:10px; padding:0px;" method="post">');
             _form.push('<input type="hidden" name="path" class="path"  id="img_path" />');
             _form.push('<input name="txt_width" type="hidden" value="300" id="txt_width" />');
             _form.push('<input name="txt_height" type="hidden" value="300" id="txt_height" />');
             _form.push('<input name="txt_top" type="hidden" value="0" id="txt_top" /> <input name="txt_left" type="hidden" value="0" id="txt_left" />');
             _form.push('<input name="txt_DropWidth" type="hidden" value="200" id="txt_DropWidth" /> <input name="txt_DropHeight" type="hidden" value="200" id="txt_DropHeight" />');
             _form.push('</form>');

            $("body").append( $(_form.join("")));
        }
    },
    _createCutDialog: function(){
        if($("#crop_container").length == 0 ) {
            // <span class="pictitle">头像设置</span>\
            $("body").append( $(_cutDialog) );
        }
    },
    _initDomListener: function(){
        var me = this;
        var saveBtn = $("#save_pic");
        saveBtn.off().on("click", function(){
            me.saveImg(this, me.callback);
        })

        var cancelBtn = $("#pic_not");
        cancelBtn.off().on("click", function(){
            me.cancelCut(this);
        })

    },

    
    loadImg: function(){
        var me = this;
        var img = new Image();
        img.onload = function(){
            me.reCountImg(img);
            me.opearteImg();
        };
        if(!img.complete){
            var t = setInterval(function(){
                if(img.complete){
                    me.reCountImg(img);
                    me.opearteImg();
                    clearInterval(t);
                    return false;
                }
            },500)
        }

        me.Picurl = me.Picurl+"?v="+new Date().getTime();
        img.src =  me.Picurl;
    },
    opearteImg: function(){
        var me = this;
        //$.colorbox({inline:true, href:"#crop_container",title:"图片剪切" ,width:750, height:700})
        $(".crop-container").show();
        var src = me.Picurl;
        $("#crop-photo").attr("src",src);
        $("#"+me._saveformId).find(".path").attr("value",me.absPath);
        var imgs = $(".preview-right img");
        $.each(imgs, function(index, val) {
            var img  = $(this);
            img.attr("src",src);
        });
        var coordinate = this.getCoordinate();
        avaInstance =  $('#crop-photo').imgAreaSelect({
            aspectRatio: '1:1',
            onSelectChange: me.previewImages,
            onSelectEnd: me.endCrop,
            instance: true,
            maxWidth: 150,
            maxHeight: 150,
            show: true,
            movable: true,
           // onInit: me.previewImages,
            x1: coordinate.x1,
            x2: coordinate.x2,
            y1: coordinate.y1,
            y2: coordinate.y2
        });

        // 上传图片没有初始化预览及剪切的位置 add by zhanghaibing on 2016/1/27
        me.initPrevieImages(null,avaInstance);

    },
    preview: function(width,img, selection) {
        var scaleX = width / (selection.width || 1);
        //  Modify by zhb 修改上传背景图片侧边显示不正确的BUG
        var scaleY = width / (selection.width/selection.height * selection.height || 1);
        var w = $("#crop-photo").width();
        var h = $("#crop-photo").height();
       img.css({
            width : Math.round(scaleX * w) + 'px',
            height : Math.round(scaleY * h) + 'px',
            marginLeft : '-' + Math.round(scaleX * selection.x1) + 'px',
            marginTop : '-' + Math.round(scaleY * selection.y1) + 'px'
        });
    },

     previewImages: function(img,selection){
         var me = xy_imgCrop;
        var imgs = $(".preview-right img");

        $.each(imgs, function(index, val) {
            var i  = $(this);
            var width = i.attr("data-w");
            me.preview(width,i,selection)
        });

    },

     endCrop: function(img, selection) {
        $("#txt_width").val($("#crop-photo").width());
        $("#txt_height").val($("#crop-photo").height());
        $("#txt_top").val(selection.y1);
        $("#txt_left").val(selection.x1);
        $("#txt_DropWidth").val(selection.width);
        $("#txt_DropHeight").val(selection.height);
    },

     getNaturalSize: function() {
        var screenImage = $("#crop-photo");
        var theImage = new Image();
        theImage.src = screenImage.attr("src");
        var imageWidth = theImage.width;
        var imageHeight = theImage.height;
        return [ imageWidth, imageHeight ];
    },
    /**
     * 获取选择框坐标
     * @returns {{x1: (*|avaInstance.x1|selection.x1|jQuery.imgAreaSelect.getSelection.x1|jQuery.imgAreaSelect.doMove.x1), x2: (*|avaInstance.x2|option1.grid.x2|option3.grid.x2|selection.x2|jQuery.imgAreaSelect.getSelection.x2), y1: (*|avaInstance.y1|selection.y1|jQuery.imgAreaSelect.getSelection.y1|jQuery.imgAreaSelect.doMove.y1), y2: (*|avaInstance.y2|option1.grid.y2|option3.grid.y2|selection.y2|jQuery.imgAreaSelect.getSelection.y2)}}
     */
    getCoordinate: function(){
        var me = xy_imgCrop;
        var w = $("#crop-photo").width();
        var h = $("#crop-photo").height();
        var z = null;
            if (w < 150 || h < 150) {
                var min = Math.min(w, h);
                z={
                    x1:w/2-min/2,
                    y1:h/2-min/2,
                    x2:w/2+min/2,
                    y2:h/2+min/2
                };
            }else{
                z={
                    x1:w/2-75,
                    y1:h/2-75,
                    x2:w/2+75,
                    y2:h/2+75
                };
            }
        return {x1:z.x1,x2:z.x2,y1:z.y1,y2:z.y2};
    },
     initPrevieImages: function(img, avaInstance){
         var me = xy_imgCrop;
         var z = me.getCoordinate();
         avaInstance.setSelection(z.x1,z.y1,z.x2,z.y2);
         avaInstance.setOptions({ show: true });
         avaInstance.update(true);
         me.previewImages(img,avaInstance.getSelection());
         me.endCrop(img,avaInstance.getSelection())
    },
    _initImgUploader: function(){
        var me = this;
        var uploadURL = "/static/.tmp/"
        var button = $("#" + this.fileBtnId);
        var allowExtention = ".jpg,.bmp,.png";
       
       button.change(function(){
           //同时存在多个可上传选框时，用id区别form表单
           me.initParam(me.paramsObj[this.id]);
            var allowExtention = ".jpg,.bmp,.png";
            var fileName = button.val();
            arr = fileName.split("\\");
            fileName = arr[arr.length - 1];
            var extention = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (allowExtention.indexOf(extention) == -1) {
                allowExtention
                alertDIV(xy_util.getMessage(STATICMSG["1019"], allowExtention));
                return false;
            }
            xy_util.lockScreen();
            $.ajaxFileUpload({
                url: '/upload/photo/', // 用于文件上传的服务器端请求地址
                secureuri: false, // 是否需要安全协议，一般设置为false
                fileElementId: me.fileBtnId, // 文件上传域的ID
                dataType: 'text', // 返回值类型 一般设置为json
                type: 'post',
                success: function (result) { // 服务器成功响应处理函数
                    xy_util.hideLock();
                        if(!xy_util.isIe()){
                            result = JSON.parse(result);
                        }
                    me.Picurl =  uploadURL + result.data;
                    //不带ip与端口号的地址
                    me.absPath = result.data;

                    $("#"+me.params.dataId).val( result.data);
                    me.loadImg();

                }
            });
        })
    },
    // 截取头像
    saveImg: function(obj,callback){
        var me = this;
         var uploadURL = "/static/.tmp/"
        xy_util.lockScreen();
        $.ajax({
            url: '/crop/photo/', // 用于文件上传的服务器端请求地址,跨主域上传
            dataType : "text",//数据类型为jsonp
            data:$("#"+me._saveformId).serialize(),// 你的formid
            success: function(result){
               // if(!xy_util.isIe()){
                    result = JSON.parse(result);
               // }
                     xy_util.hideLock();
                    avaInstance.cancelSelection();
                    $(obj).parents(".crop-container").hide();
                    xy_util.hideLock();
                    var phopathimg=uploadURL+result.data +"?v="+new Date().getTime();
                    xy_util.onloadImg(phopathimg, function(src){
                        me.displayImg.show().attr({"src":src,"data-src":src});
                    })
                    //重新初始化，修复只能点击一次的问题
                    me.init(me.params);
                    if(callback && typeof callback == "function"){
                        callback(phopathimg);
                    }

         }
        })
    },
    cancelCut: function(obj){
        $(obj).parents(".crop-container").hide();
        xy_util.hideLock();
        avaInstance.cancelSelection();
        //重新初始化，修复只能点击一次的问题
        this.init(this.params);
    },
    /**
     * 重新计算图片的宽高，按比例缩放
     */
    reCountImg: function(img){
        var w = $(".crop-container").find(".box").width();//容器宽度
        var h = $(".crop-container").find(".box").height();//容器宽度
        var img_w,img_h;

        //低版本的ie没有naturalWidth属性
        var lowIEVersion = $.browser.msie && parseInt($.browser.version);
        if(lowIEVersion < 10){
            img_w =  img.width;
            img_h =  img.height;
        }else{
            img_w = $(img)[0].naturalWidth;//图片宽度
            img_h = $(img)[0].naturalHeight;//图片高度
        }

        var height,width,top = 0;

        if(img_w > w || img_h > h){
            if(img_w>=img_h){//按宽度等比缩放
                height = (img_h*w)/img_w;
                width = w;
            }else{
                width = (img_w*h)/img_h;
                height = h;
            }
        }else{
            height = img_h;
            width = img_w;
        }
        top = (h - height)/2;
        $("#crop-photo").css({"width":width,"height":height,"margin-top":top});//设置缩放后的宽度和高度
    }
}

return xy_imgCrop;

})

